<?php

namespace Modules\Custessa\Services;

use DB;
use APP;

class ContentOutput {

    const TYPE_CSS = '.css';
    const TYPE_JS = '.js';
    const HEADER_CONTENT_TYPE = [
        self::TYPE_JS => 'application/javascript',
        self::TYPE_CSS => 'text/css',
    ];

    static protected $modules = [];
    static protected $manifests = [];

    /**
     * Get relative path of enabled modules.
     */
    public function __construct() {
        $modules = DB::select('module', [
            'output' => ['id', 'relative_path'],
            'filter' => ['status' => MODULE_STATUS_ENABLED]
        ]);
        self::$modules = array_column($modules, 'relative_path', 'id');
    }

    /**
     * Send requested files contentent to output. Also set Content-Type header according $type.
     *
     * @param string $type     One of ContentOuput::TYPE_* constants.
     * @param string $assets   String with requested module assets files.
     */
    public function render(string $type, string $assets) {
        if (self::HEADER_CONTENT_TYPE[$type]) {
            header('Content-Type: '.self::HEADER_CONTENT_TYPE[$type]);
        }

        $assets = explode(',', $assets);
        $root_dir = APP::getRootDir().'/modules';

        foreach ($assets as $asset) {
            [$module, $file] = explode(':', $asset, 2);
            $module = self::$modules[$module] ?? null;

            if ($module === null) {
                // Disallow to include disabled or non existing module asset files.
                continue;
            }

            if (!isset(self::$manifests[$module])) {
                $path = $root_dir."/{$module}/manifest.json";
                $manifests[$module] = json_decode(file_get_contents($path), true);
            }

            if (in_array($file.$type, (array) $manifests[$module]['assets'] ?? [])) {
                echo file_get_contents($root_dir."/{$module}/assets/{$file}{$type}");
            }
        }
    }
}